package com.taskmanagement.controller;

import com.taskmanagement.dto.AuthResponse;
import com.taskmanagement.dto.LoginRequest;
import com.taskmanagement.dto.RegisterRequest;
import com.taskmanagement.service.AuthService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthService authService;

    @PostMapping("/login")
    public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest,
                                              BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            Map<String, String> errors = new HashMap<>();
            bindingResult.getFieldErrors().forEach(error ->
                    errors.put(error.getField(), error.getDefaultMessage())
            );
            return ResponseEntity.badRequest().body(errors);
        }

        try {
            logger.info("用户登录请求: {}", loginRequest.getUsername());
            AuthResponse authResponse = authService.login(loginRequest);
            return ResponseEntity.ok(authResponse);
        } catch (Exception e) {
            logger.error("登录失败: ", e);
            return ResponseEntity.badRequest().body("登录失败: " + e.getMessage());
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody RegisterRequest registerRequest) {
        try {
            logger.info("用户注册请求: {}", registerRequest.getEmail());
            AuthResponse authResponse = authService.register(registerRequest);
            logger.info("用户注册成功: {}", registerRequest.getEmail());
            return ResponseEntity.ok(authResponse);
        } catch (Exception e) {
            logger.error("注册失败: ", e);
            return ResponseEntity.badRequest().body("注册失败: " + e.getMessage());
        }
    }
    @PostMapping("/logout")
    public ResponseEntity<?> logoutUser(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        try {
            logger.info("用户登出请求");

            // 从 Authorization 头部提取 token
            String token = null;
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                token = authHeader.substring(7);
            }

            // 调用服务层处理登出逻辑
            authService.logout(token);

            logger.info("用户登出成功");
            return ResponseEntity.ok(Map.of("message", "登出成功"));
        } catch (Exception e) {
            logger.error("登出失败: ", e);
            return ResponseEntity.badRequest().body("登出失败: " + e.getMessage());
        }
    }

}
